//signUp.js
import $ from '../utils';
import mongoDB from '../mongodb';


function Main() {
    this.signUp = async (data) =>{
        let queryData = {"username":data.username};
        let result = await mongoDB.mongoFunc.findData(queryData,'f_message_user');


        // console.log((await mongoDB.mongoFunc.findData({},'sessions'))[0]._id)
        // console.log(JSON.parse((await mongoDB.mongoFunc.findData({},'sessions'))[0].session).token)

        if(result.length>0){
            return(JSON.stringify({"status":'0',"msg":'用户名已经存在',"dataset":[]}));
        }else{
            let result = await mongoDB.mongoFunc.insertData(data,'f_message_user');
            if(result){
                let user_json = await mongoDB.mongoFunc.findData(queryData,'f_message_user');
                let object = {'username':user_json[0].username,'loginTime':user_json[0].loginTime,'user_id':user_json[0].user_id}
                return(JSON.stringify({"status":'1',"msg":'注册成功',"dataset":[object]}))
            }
        }
    }
    this.login = async (data) => {
        let queryData = {"username":data.username};
        let result = await mongoDB.mongoFunc.findData(queryData,'f_message_user');
        if(result.length>0){
            let cryptPass = await $.baseFunc.cryptPwd(data.pass);
            if(result[0].password == cryptPass){
                let keyData = queryData;
                let updateData = {'loginTime':$.base.currentTime()};
                let result = await mongoDB.mongoFunc.updateData(keyData,updateData,'f_message_user')
                if(result){
                    let user_json = await mongoDB.mongoFunc.findData(keyData,'f_message_user');
                    let object = {'username':user_json[0].username,'loginTime':user_json[0].loginTime,'user_id':user_json[0].user_id}

                    return(JSON.stringify({"status":'1',"msg":'登陆成功',"dataset":[object]}))
                }
            }else{
                return(JSON.stringify({"status":'0',"msg":'密码错误',"dataset":[]}))
            }
        }else{
            return(JSON.stringify({"status":'0',"msg":'用户名不存在',"dataset":[]}))
        }
    }
};

module.exports = Main;